from sqlalchemy.orm import Session
from module_admin.entity.do.cms_expense import CmsExpense
from module_admin.entity.vo.expense_vo import ExpensesModel, ExpensePageObject
from utils.time_format_util import object_format_datetime, list_format_datetime
from utils.uuid import UUID


class CmsExpenseDao:

    @classmethod
    def create_expense(cls, db: Session, add_object: ExpensesModel):
        uuid = UUID().uuid()
        add_object.id = int(uuid)
        cms_expense = CmsExpense(**add_object.dict())
        db.add(cms_expense)
        db.flush()
        return cms_expense

    @classmethod
    def delete_expense_by_id(cls, db: Session, expense_id: int):
        db.query(CmsExpense) \
            .filter(CmsExpense.id == expense_id) \
            .delete()
        db.commit()

    @classmethod
    def update_expense_by_id(cls, db: Session, expense_update_dict: dict):
        db.query(CmsExpense) \
            .filter(CmsExpense.id == expense_update_dict.get('id')) \
            .update(expense_update_dict)

    @classmethod
    def get_one_by_car_type(cls, db: Session, car_type: str, car_brand: str):
        first = (db.query(CmsExpense)
                 .filter(CmsExpense.car_type == car_type)
                 .filter(CmsExpense.car_brand == car_brand)
                 .first())
        return object_format_datetime(first)
    @classmethod
    def page(cls, db, query_object: ExpensePageObject):
        page_num = query_object.page_num
        page_size = query_object.page_size
        skip = (page_num - 1) * page_size  # 计算跳过的记录数
        limit = page_size  # 每页返回的记录数
        query = db.query(CmsExpense)
        filters = []
        if query_object.car_type and query_object.car_type.strip():
            filters.append(CmsExpense.car_type.like(f'%{query_object.car_type}%'))
        if filters:
            query = query.filter(*filters)
        post_list = query.order_by(CmsExpense.create_time.desc()).offset(skip).limit(limit).all()
        return list_format_datetime(post_list)

    @classmethod
    def count(cls, db, query_object: ExpensePageObject):
        query = db.query(CmsExpense)
        filters = []
        if query_object.car_type and query_object.car_type.strip():
            filters.append(CmsExpense.car_type.like(f'%{query_object.car_type}%'))
        if filters:
            query = query.filter(*filters)
        return query.order_by(CmsExpense.create_time.desc()).count()
